package com.tensquare.user.interceptor;

import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (StrUtil.isNotEmpty(authorization) && authorization.startsWith("Bearer ")){
            String token=authorization.substring(7);
            Claims claims = jwtUtils.getClaims(token);
            if (claims!=null){
                request.setAttribute("claims",claims);
            }
        }
        return true;
    }
}
